<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        window.onload = function () {
            /**
             *实现鼠标拖拽效果
             * 步骤：
             * 1、鼠标按下：绑定给box1
             * 2、鼠标移动: 绑定给document
             * 3、鼠标松开: 绑定给box1
             */
            var box1 = document.getElementById("box1");
            box1.onmousedown = function (event) {
                event = event || window.event;
                //div偏移量
                // 鼠标.clientX - box1.offsetLeft
                // 鼠标.clientY - box1.offsetTop
                //clientX: 鼠标相对于浏览器窗口的X坐标
                //offsetLeft: div相对于浏览器窗口的X坐标
                var ol = event.clientX - box1.offsetLeft;
                var ot = event.clientY - box1.offsetTop;

                //2、鼠标移动: 绑定给document
                //获取鼠标位置
                document.onmousemove = function (event) {
                    event = event || window.event; //兼容性处理

                    //获取鼠标位置
                    var x = event.clientX - ol;
                    var y = event.clientY - ot;

                    //改变盒子的位置
                    box1.style.left = x + "px";
                    box1.style.top = y + "px";
                }

                // 3、鼠标松开: 绑定给document，移除移动事件和鼠标松开事件
                document.onmouseup = function () {
                    //取消移动事件
                    document.onmousemove = null;
                    //取消鼠标按下事件
                    document.onmousedown = null;
                }
            }
        }

    </script>


</head>
<body>
<div id="box1"></div>
<div id="box2"></div>

</body>
<style>
    #box1 {
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
    }

    #box2 {
        width: 100px;
        height: 100px;
        background-color: yellow;
        position: absolute;

        left: 200px;
        top: 200px;
    }
</style>

</html>
